package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Description ResourceServiceImpl
 * @Author Wen Jie
 * @Date 2024-09-15
 */
@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;
    @Override
    public List<ResourceVo> list(ResourceVo resourceVo) {
        List<Resource> resources = resourceMapper.list(resourceVo);
        List<ResourceVo> resourceVos = BeanUtil.copyToList(resources, ResourceVo.class);
        return resourceVos;
    }

    @Override
    public TreeVo resourceTreeVo(ResourceVo resourceVo) {
        //1.构建查询条件
        ResourceVo vo = ResourceVo.builder()
                .parentResourceNo(NoProcessing.processString(SuperConstant.ROOT_DEPT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .build();
        //2、查询所有资源数据
        List<Resource> resourceList = resourceMapper.list(vo);
        if (EmptyUtil.isNullOrEmpty(resourceList)) {
            throw new RuntimeException("资源数据为空");
        }
        //3.定义树形集合
        List<TreeItemVo> itemVos = new ArrayList<>();
        //4.使用hutool工具获取树形结构
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        //自定义名称由原有的name改成label
        treeNodeConfig.setNameKey("label");
        //利用hutools中的菜单功能实现
        List<Tree<String>> treeList = TreeUtil.build(resourceList, SuperConstant.ROOT_PARENT_ID, treeNodeConfig,
                (resource, treeItemVo) -> {
                    treeItemVo.setName(resource.getResourceName());
                    treeItemVo.setId(resource.getResourceNo());
                    treeItemVo.setParentId(resource.getParentResourceNo());
                });
        List<TreeItemVo> children = BeanUtil.copyToList(treeList, TreeItemVo.class);
        TreeItemVo itemVo = TreeItemVo.builder()
                .id(SuperConstant.ROOT_DEPT_PARENT_ID).label("智慧养老院").children(children).build();
        itemVos.add(itemVo);
        return TreeVo.builder().items(itemVos).build();
    }

    @Override
    public void createResource(ResourceDto resourceDto) {
        Resource parentResource = resourceMapper.selectByParentResourceNo(resourceDto.getParentResourceNo());
        //2.类型转换拷贝
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //3.同步父资源状态和子资源状态一致
        resource.setDataState(parentResource.getDataState());
        //4.创建子编号
        resource.setResourceNo(createResourceNo(resource));
        //5.调用新增
        resourceMapper.insert(resource);

    }

    private String createResourceNo(Resource resource) {
        /**
         * 1、如果是菜单，以及父资源编号是否大于三级，说白就是暂时只支持最多三级菜单，不能创建四级菜单
         */
        if (resource.getResourceType().equals("m") &&
                NoProcessing.processString(resource.getParentResourceNo()).length() / 3 == 5) {
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
        //2.查询父资源编号下是否包含子资源
        ResourceVo vo = ResourceVo.builder().parentResourceNo(resource.getParentResourceNo()).build();
        List<Resource> resources = resourceMapper.list(vo);
        if (EmptyUtil.isNullOrEmpty(resources)) {
            //3.如果父资源编号下没有子资源，则新增  100 001 001 001 000--->新增下属节点100 001 001 001 001
            return NoProcessing.createNo(resource.getParentResourceNo(), false);
        } else {
            //4.有下属节点，则在原有基础上追加 100 001 001 001 001--->追加之后，100 001 001 001 002
            // 要先获取下属节点中的最大值
            Long max = resources.stream().map(resource1 -> {
                return Long.valueOf(resource1.getResourceNo());
            }).max(Comparator.comparing(Long::intValue)).get();
            return NoProcessing.createNo(max.toString(), true);
        }
    }

    @Override
    public void updateResource(ResourceDto resourceDto) {
        Resource resource = BeanUtil.copyProperties(resourceDto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    @Override
    @Transactional
    public boolean isEnable(ResourceDto resourceDto) {
        if (resourceDto.getDataState().equals("0")) {
            //判断父级菜单是否是禁用，如果是禁用，不允许启用
            String parentResourceNo = resourceDto.getParentResourceNo();
            Resource parentResource = resourceMapper.getByResourceNo(parentResourceNo);
            if (parentResource != null && parentResource.getDataState().equals("1")){
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }
        int count = roleResourceMapper.checkMenuExistRole(resourceDto.getResourceNo());
        if(resourceDto.getDataState().equals("1") && count > 0){
            Resource resource = resourceMapper.getByResourceNo(resourceDto.getResourceNo());
            if (resource.getResourceType().equals("m")){
                throw new BaseException(BasicEnum.MENU_DISTRIBUTED);
            }else {
                throw new BaseException(BasicEnum.BUTTON_DISTRIBUTED);
            }
        }
        String resourceNo = resourceDto.getResourceNo();
        resourceMapper.updateByResourceNo(resourceNo,resourceDto.getDataState());
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo),resourceDto.getDataState());
        return true;
    }
}

